<template>
  <CustomScrollbar class="recent-scroll">
    <div class="recent">
    <h1 class="page-title">最近播放</h1>
    
    <div v-if="recentSongs.length === 0" class="empty-state">
      <div class="empty-icon">🕒</div>
      <h3>还没有播放记录</h3>
      <p>开始播放一些音乐，它们会显示在这里</p>
      <button class="browse-btn" @click="$router.push('/')">浏览音乐</button>
    </div>
    
    <div v-else class="songs-list">
      <div class="song-item" v-for="(song, index) in recentSongs" :key="song.id">
        <div class="song-rank">{{ index + 1 }}</div>
        <img v-if="song.cover" :src="song.cover" :alt="song.name" class="song-thumbnail">
        <MusicIcon v-else :size="48" class="song-thumbnail" />
        <div class="song-details">
          <div class="song-name">{{ song.name }}</div>
          <div class="song-artist">{{ song.singer }}</div>
        </div>
        <div class="song-album">{{ song.album || '未知专辑' }}</div>
        <div class="play-time">{{ formatDate(song.playTime) }}</div>
        <div class="song-duration">{{ formatDuration(song.duration) }}</div>
        <div class="song-actions">
          <button class="action-btn" @click="toggleFavorite(song)" 
                  :class="{ 'favorited': isFavorite(song.id) }" title="收藏/取消收藏">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
            </svg>
          </button>
          <button class="action-btn" @click="playMusic(song)">▶</button>
        </div>
      </div>
    </div>
    </div>
  </CustomScrollbar>
</template>

<script>
import MusicIcon from '@/components/MusicIcon.vue'
import CustomScrollbar from '@/components/CustomScrollbar.vue'
import { playlistAPI } from '@/utils/api'

export default {
  components: {
    MusicIcon,
    CustomScrollbar
  },
  name: 'RecentView',
  data() {
    return {
      recentSongs: []
    }
  },
  async mounted() {
    // 加载收藏列表
    await this.$store.dispatch('player/loadFavorites')
    
    await this.loadRecentMusic()
  },
  methods: {
    async loadRecentMusic() {
      try {
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        
        if (userToken && userToken !== 'null' && userToken !== '' && userToken.length > 20 && userExpiry && Date.now() < parseInt(userExpiry)) {
          const response = await playlistAPI.getPlayHistory(0, 50)
          if (response.success && response.playHistory) {
            // 映射数据并按播放时间逆序排列，最多显示30个
            let mappedSongs = response.playHistory.map(item => ({
              id: item.music.musicId,
              name: item.music.name,
              artist: item.music.singer,
              album: item.music.album || item.music.singer, // 未知专辑显示艺术家名字
              cover: item.music.coverPath,
              duration: item.music.duration,
              filePath: item.music.filePath,
              playTime: new Date(item.playTime)
            }))
            
            // 按播放时间逆序排列（最新的在前面）
            mappedSongs.sort((a, b) => b.playTime - a.playTime)
            
            // 最多显示30个
            this.recentSongs = mappedSongs.slice(0, 30)
            
            console.log('加载播放历史:', this.recentSongs.length, '首')
          }
        } else {
          console.log('前台用户未登录或token过期，不显示播放历史')
          this.recentSongs = []
        }
      } catch (error) {
        console.error('加载播放历史失败:', error)
        if (error.response?.status === 401 || error.response?.status === 403) {
          localStorage.removeItem('userToken')
          localStorage.removeItem('userInfo')
          localStorage.removeItem('userTokenExpiry')
          this.recentSongs = []
        }
      }
    },
    async playMusic(song) {
      try {
        console.log('播放音乐:', song.name)
        
        // 构建播放列表（最近播放列表）
        const playlist = this.recentSongs.map(s => ({
          musicId: s.id,
          id: s.id,
          title: s.name,
          name: s.name,
          singer: s.artist,
          artist: s.artist,
          cover: s.cover,
          coverPath: s.cover,
          duration: s.duration,
          filePath: s.filePath,
          src: s.filePath || s.src
        }))
        
        // 设置播放列表
        this.$store.commit('player/SET_PLAYLIST', playlist)
        
        // 找到当前音乐在播放列表中的索引
        const currentIndex = playlist.findIndex(item => item.musicId === song.id)
        if (currentIndex !== -1) {
          this.$store.commit('player/SET_CURRENT_INDEX', currentIndex)
        }
        
        // 调用Vuex播放音乐
        this.$store?.dispatch('player/playMusic', {
          musicId: song.id,
          id: song.id,
          title: song.name,
          name: song.name,
          singer: song.artist,
          artist: song.artist,
          cover: song.cover,
          coverPath: song.cover,
          duration: song.duration,
          filePath: song.filePath,
          src: song.filePath || song.src
        })
        
        // 如果用户已登录，记录播放历史（异步，不阻塞播放）
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        if (userToken && userToken !== 'null' && userToken !== '' && userToken.length > 20 && userExpiry && Date.now() < parseInt(userExpiry)) {
          try {
            await playlistAPI.addPlayHistory(song.id)
          } catch (historyError) {
            console.warn('记录播放历史失败:', historyError)
            if (historyError.response?.status === 401 || historyError.response?.status === 403) {
              localStorage.removeItem('userToken')
              localStorage.removeItem('userInfo')
              localStorage.removeItem('userTokenExpiry')
            }
          }
        }
      } catch (error) {
        console.error('播放音乐失败:', error)
      }
    },
    async toggleFavorite(song) {
      try {
        // 构建音乐数据对象
        const musicData = {
          musicId: song.id,
          id: song.id,
          title: song.name,
          name: song.name,
          artist: song.artist,
          singer: song.artist,
          cover: song.cover,
          duration: song.duration,
          filePath: song.filePath
        }
        
        // 使用Vuex store的toggleFavorite action
        await this.$store.dispatch('player/toggleFavorite', musicData)
        
        console.log('收藏操作成功:', song.name)
      } catch (error) {
        console.error('收藏操作失败:', error)
      }
    },
    isFavorite(songId) {
      return this.$store.getters['player/favorites'].includes(songId)
    },
    formatDuration(seconds) {
      // 处理各种输入情况
      if (seconds === null || seconds === undefined || seconds === 0) return '-'
      
      // 确保是数字类型
      const numSeconds = Number(seconds)
      if (isNaN(numSeconds) || numSeconds < 0) return '-'
      
      // 计算分钟和秒
      const minutes = Math.floor(numSeconds / 60)
      const remainingSeconds = Math.floor(numSeconds % 60)
      
      // 格式化输出
      if (minutes >= 60) {
        // 超过1小时的情况
        const hours = Math.floor(minutes / 60)
        const remainingMinutes = minutes % 60
        return `${hours}:${remainingMinutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      } else {
        // 普通情况：分:秒
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
    },
    formatDate(date) {
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) return '今天'
      if (days === 1) return '昨天'
      if (days < 7) return `${days}天前`
      
      return date.toLocaleDateString('zh-CN')
    }
  }
}
</script>

<style scoped>
.recent-scroll {
  height: 100%;
}

.recent {
  padding-bottom: 24px; /* 确保底部有适当的间距 */
}

.page-title {
  font-size: 2rem;
  margin-bottom: 32px;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 64px 32px;
  color: #b3b3b3;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 24px;
  opacity: 0.5;
}

.empty-state h3 {
  color: white;
  font-size: 2rem;
  margin-bottom: 16px;
}

.browse-btn {
  background: #1DB954;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 24px;
  font-weight: bold;
  cursor: pointer;
  margin-top: 24px;
  transition: background 0.2s;
}

.browse-btn:hover {
  background: #1ed760;
}

.songs-list {
  background: #181818;
  border-radius: 8px;
  overflow: hidden;
}

.song-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #282828;
  transition: background 0.2s;
}

.song-item:hover {
  background: #282828;
}

.song-item:last-child {
  border-bottom: none;
}

.song-rank {
  width: 32px;
  text-align: center;
  color: #b3b3b3;
  font-weight: bold;
  margin-right: 16px;
}

.song-thumbnail {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  margin-right: 16px;
}

.song-details {
  flex: 1;
  min-width: 0;
  margin-right: 16px;
}

.song-name {
  font-size: 16px;
  font-weight: 500;
  color: white;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 4px;
}

.song-artist {
  font-size: 14px;
  color: #b3b3b3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-album {
  flex: 1;
  color: #b3b3b3;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 16px;
}

.play-time {
  color: #b3b3b3;
  margin-right: 16px;
  min-width: 80px;
  text-align: right;
  font-size: 14px;
}

.song-duration {
  color: #b3b3b3;
  margin-right: 16px;
  min-width: 50px;
  text-align: right;
}

.song-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.2s;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn:hover {
  color: white;
  background: rgba(255, 255, 255, 0.1);
}

.action-btn.favorited {
  color: #1DB954 !important;
}

.action-btn.favorited svg {
  color: #1DB954 !important;
}

@media (max-width: 768px) {
  .song-album,
  .play-time {
    display: none;
  }
  
  .song-item {
    padding: 8px 12px;
  }
}
</style> 